﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TjZheng.Mvc;
using TjZheng.Framework;

namespace TjZheng.Example.MVC.Controllers
{
    public class EncryptionFilter : TjZhengFilter
    {
        //设计：
        //接口证书分类表：名称，ParentId，授权调用域，有效时间间隔
        //接口证书管理表：是否加密，密钥，令牌，授权调用域，过期时间，有效时间间隔，超时间隔，创建时间
        /// <summary>
        /// 是否加密
        /// </summary>
        protected bool IsEncrypt { get; set; }

        /// <summary>
        /// 约定密钥
        /// </summary>
        protected string EncryptKey { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="IsEncrypt">是否加密</param>
        public EncryptionFilter(bool IsEncrypt)
        {
            this.IsEncrypt = IsEncrypt;
            this.EncryptKey = GetEncryptKey();
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            InvokeResult objInvokeResult = CheckAccess(filterContext);
            if (objInvokeResult.ResultCode != "Success")
            {
                filterContext.Result = new JsonResult
                {
                    Data = objInvokeResult,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (!this.IsEncrypt)
            {
                return;
            }
            InvokeResult objInvokeResult = new InvokeResult();
            if (!(filterContext.Result is JsonResult) && !(filterContext.Result is JsonpResult) && !(filterContext.Result is ContentResult))
            {
                objInvokeResult.ResultCode = "ReturnError";
                objInvokeResult.ResultMessage = "返回结果格式错误";
                filterContext.Result = new JsonResult
                {
                    Data = objInvokeResult,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }
            if (filterContext.Result is JsonResult)
            {
                JsonResult objJsonResult = filterContext.Result as JsonResult;
                objInvokeResult.Data = EncryptHandle(objJsonResult.Data.JsonSerialize());
                objJsonResult.Data = objInvokeResult;
                return;
            }
            if (filterContext.Result is JsonpResult)
            {
                JsonpResult objJsonpResult = filterContext.Result as JsonpResult;
                objInvokeResult.Data = EncryptHandle(objJsonpResult.Data.JsonSerialize());
                objJsonpResult.Data = objInvokeResult;
                return;
            }
            ContentResult objContentResult = filterContext.Result as ContentResult;
            objInvokeResult.Data = EncryptHandle(objContentResult.Content);
            filterContext.Result = new JsonResult
            {
                Data = objInvokeResult,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 自定义访问权限
        /// </summary>
        /// <returns></returns>
        public virtual InvokeResult CheckAccess(ActionExecutingContext filterContext)
        {
            //return new InvokeResult();
            InvokeResult objInvokeResult = new InvokeResult();
            int SignTime = GetInt("SignTime");
            int TimeTout = GetInt("TimeTout");
            int CurrentTime = DateTime.Now.ConvertToSecondStamp();
            if (TimeTout > 0 && (CurrentTime - SignTime) > TimeTout)
            {
                objInvokeResult.ResultCode = "TimeOut";
                objInvokeResult.ResultMessage = "签名已过期";
                return objInvokeResult;
            }
            string SignatureSource = GetString("Signature");
            //签名
            string Signature = (SignTime.ToString() + TimeTout.ToString() + this.EncryptKey).EncodeMD5();
            if (!string.Equals(SignatureSource, Signature))
            {
                objInvokeResult.ResultCode = "SignIllegal";
                objInvokeResult.ResultMessage = "签名非法";
                return objInvokeResult;
            }
            return objInvokeResult;
        }

        /// <summary>
        /// 自定义获取密钥方法，设置this.EncryptKey值
        /// </summary>
        protected virtual string GetEncryptKey()
        {
            return "";
        }

        /// <summary>
        /// 自定义加密算法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected virtual string EncryptHandle(string data)
        {
            return (this.EncryptKey + data).EncodeBase64();//
        }
    }
}